package EGS.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;

import javax.swing.JTable;

import org.dom4j.Document;
import org.dom4j.Element;

import LOGISTICS.c_material;
import LOGISTICS.m_material;
import TOOLS.SQLtool;
import TOOLS.errCodeManagement;
import WORKPLACE.stationClient;

public class EGS_execute_service10018Impl{
	public boolean isUnknowCase = false;
	ExecutorService iExecutorService;
	Document MSG;
	boolean isPanel = false;
	stationClient iClient=null;
	SQLtool sql = null;
	/**
	 * 511 物料信息查询
	 */
	public EGS_execute_service10018Impl(stationClient nClient, Document MSG_in, ExecutorService executorService, 
			SQLtool goldenSql) throws Exception {
		super();
		sql=goldenSql;
		if(nClient!=null) {
			iClient=nClient;
		}else {
			iClient=null;
		}
		MSG = MSG_in;
		iExecutorService = executorService;
	}

	public Document runCal() {
		String msgClass = "";
		try {
			if (MSG == null) {
				return null;
			}
			Element Mroot = MSG.getRootElement();
			msgClass = Mroot.element("header").attribute("messageClass").getValue();
			String transactionID = Mroot.element("header").attribute("transactionID").getValue();
			String iStation, iSN;

			iStation = Mroot.element("header").element("location").attribute("equipmentName").getValue();

			if (msgClass.equals("10018")) {// 511 物料信息查询
				iSN = Mroot.element("body").element("material").attribute("id").getValue();
				String isOffLine = Mroot.element("body").element("offline").attribute("value").getValue();
				try {
					Mroot.remove(Mroot.element("body"));
					Mroot.addElement("body");
				} catch (Exception e1) {
					;
				}
				Element eleR = Mroot.element("body").addElement("result");
				try {
					SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					c_material cm = new c_material(sql);
					m_material iReel = null;
					try {
						iReel = cm.getMaterial(iSN);
					} catch (Exception e) {
						if (e.getMessage().equals("-174")) {// 获取不到就100004来凑
							String[] pickOrder = null;
							Vector<String> inputs = new Vector<String>();
							isPanel = false;
							JTable t = sql.select("select orderNumber from assetStation where ID='" + iStation + "'");
							if (t == null || t.getRowCount() < 1) {
								throw e;
							}
							String oOrder = (String) t.getValueAt(0, 0);
							Thread iTH = new Thread(new Runnable() {
								String orderNo = oOrder;
								@Override
								public void run() {
									String str = "select masterOrderNumber from vOrderList_new "
											+ "where panelOrderNumber='" + orderNo + "' group by masterOrderNumber";
									try {
										JTable t = sql.select(str);
										if (t != null && t.getRowCount() > 0) {
											isPanel = true;
											for (int i = 0; i < t.getRowCount(); i++) {
												String iOrder = (String) t.getValueAt(i, 0);
												inputs.add(iOrder);
											}
										}
									} catch (Exception e) {
										;
									}
								}
							});

							Thread iTH1 = new Thread(new Runnable() {
								String orderNo = oOrder;
								@Override
								public void run() {
									String str = "select masterOrderNumber from vOrderList_new "
											+ "where masterOrderNumber='" + orderNo + "' group by masterOrderNumber";
									try {
										JTable t = sql.select(str);
										if (t != null && t.getRowCount() > 0) {
											for (int i = 0; i < t.getRowCount(); i++) {
												String iOrder = (String) t.getValueAt(i, 0);
												inputs.add(iOrder);
											}
										}
									} catch (Exception e) {
										;
									}
								}
							});
							iTH.start();
							iTH1.start();

							iTH.join();
							if (isPanel == false) {
								iTH1.join();
							}

							if (oOrder==null || oOrder.length()<1) {
								throw new Exception("当前工位"+iStation+"未激活工单");
							}
							
							if (inputs.isEmpty()) {
								throw new Exception("工单" + oOrder + "不存在");
							}

							pickOrder = new c_material(sql).getPickListOrders_mergeNo(inputs);
							if (pickOrder == null) {
								throw new Exception("WMS工单" + inputs + "不存在");
							}
							Vector<String> sonOrders = new Vector<String>();
							String strPickOrders = "";
							for (int i = 0; i < pickOrder.length; i++) {
								if (pickOrder[i] != null && pickOrder[i].length() > 0
										&& sonOrders.indexOf(pickOrder[i]) < 0) {
									sonOrders.add(pickOrder[i]);
									if (sonOrders.size() == 1) {
										strPickOrders = "'" + pickOrder[i] + "'";
									} else {
										strPickOrders = strPickOrders + ",'" + pickOrder[i] + "'";
									}
								}
							}
							strPickOrders = "(" + strPickOrders + ")";
							new c_material(sql).getPickResult_groups(strPickOrders);
							iReel = cm.getMaterial(iSN);
						} else {
							throw e;
						}
					}
					if (isOffLine.equals("0")) {
						if (iReel.partType.MSDvalidity > 0 && iReel.partType.MSDvalidity < 525600) {// 单位分钟，MDS大于零且小于一年的需要按MSD管理
							if (iReel.MSD_openTime == null) {
								throw new Exception("-175");
							}

						}
					}
					Element elePreReel = null;
					Element elePreReelDT = null;
					if ((iReel.preReel != null) && (iReel.preReel.length() > 1)) {
						List<m_material> preReelList = new ArrayList<m_material>();
						Vector<String> preReels = new Vector<String>();
						m_material reelCounter = iReel;
						preReels.add(iReel.materialID);
						while ((reelCounter.preReel != null) && (reelCounter.preReel.length() > 1)) {
							if (preReels.indexOf(reelCounter.preReel) < 0) {
								preReels.add(reelCounter.preReel);
								reelCounter = cm.getMaterial(reelCounter.preReel);
								preReelList.add(reelCounter);
							} else {
								reelCounter.preReel = "";
							}
						}
						int preLen = preReelList.size();
						for (int il = 0; il < preLen; il++) {
							elePreReel = Mroot.element("body").addElement("material");
							m_material preReel = preReelList.get(preLen - il - 1);
							elePreReel.addAttribute("id", preReel.materialID);
							elePreReel.addAttribute("state", "0");
							if (preReel.MSD_openTime != null) {
//								long remainTime = (preReel.MSD_invalidTime.getTime() - new Date().getTime()) / 1000/ 60;
								long remainTime = (preReel.MSD_invalidTime.getTime() - new Date().getTime()) / 1000;
								if (remainTime == 0) {
									remainTime = -1;
								}
								elePreReel.addAttribute("remainTime", "" + remainTime);
								elePreReel.addAttribute("unpackDate", fm.format(preReel.MSD_openTime));
							} else {
								elePreReel.addAttribute("remainTime", "0");
								elePreReel.addAttribute("unpackDate", "");
							}
							elePreReel.addAttribute("prevReelId", preReel.preReel);
							elePreReel.addAttribute("splicedReelId", preReel.nextReel);
							elePreReelDT = elePreReel.addElement("detail");
							elePreReelDT.addAttribute("part", preReel.partType.part.partNumber);
							elePreReelDT.addAttribute("Opart", preReel.partType.Opart.partNumber);
							elePreReelDT.addAttribute("qty", "" + preReel.quantity);
							elePreReelDT.addAttribute("lot", preReel.lotNumber);
							elePreReelDT.addAttribute("vendor", preReel.supplyerPart);
							elePreReelDT.addAttribute("userdata", "");
							elePreReelDT.addAttribute("partclass", "");
							elePreReelDT.addAttribute("msdlevel", preReel.partType.MSDlevel);
							elePreReelDT.addAttribute("standardTime", "" + preReel.partType.MSDvalidity);
							elePreReelDT.addAttribute("lowerlimit", "" + preReel.partType.MSDthreshold);
						}
					}
					Element eleIReel = Mroot.element("body").addElement("material");
					eleIReel.addAttribute("id", iReel.materialID);
					eleIReel.addAttribute("state", "0");
					if (iReel.MSD_openTime != null) {
//						long remainTime = (iReel.MSD_invalidTime.getTime() - new Date().getTime()) / 1000 / 60;
						long remainTime = (iReel.MSD_invalidTime.getTime() - new Date().getTime()) / 1000 ;
						if (remainTime == 0) {
							remainTime = -1;
						}
						eleIReel.addAttribute("remainTime", "" + remainTime);
						eleIReel.addAttribute("unpackDate", fm.format(iReel.MSD_openTime));
					} else {
						eleIReel.addAttribute("remainTime", "0");
						eleIReel.addAttribute("unpackDate", "");
					}
					eleIReel.addAttribute("prevReelId", iReel.preReel);
					eleIReel.addAttribute("splicedReelId", iReel.nextReel);
					Element eleIReelDT = eleIReel.addElement("detail");
					eleIReelDT.addAttribute("part", iReel.partType.part.partNumber);
					eleIReelDT.addAttribute("Opart", iReel.partType.Opart.partNumber);
					eleIReelDT.addAttribute("qty", "" + iReel.quantity);
					eleIReelDT.addAttribute("lot", iReel.lotNumber);
					eleIReelDT.addAttribute("vendor", iReel.supplyerPart);
					eleIReelDT.addAttribute("userdata", "");
					eleIReelDT.addAttribute("partclass", "");
					eleIReelDT.addAttribute("msdlevel", iReel.partType.MSDlevel);
					eleIReelDT.addAttribute("standardTime", "" + iReel.partType.MSDvalidity);
					eleIReelDT.addAttribute("lowerlimit", "" + iReel.partType.MSDthreshold);
					eleR.addAttribute("errorCode", "0");
					eleR.addAttribute("errorText", "Valid");
					eleR.addAttribute("actionCode", "0");
					AKSLogs(100181, "" + iSN + "_" + iStation);
				} catch (Exception e) {
					String str = errCodeManagement.getErrText(e.getMessage());
					eleR.addAttribute("errorCode", "1");
					eleR.addAttribute("errorText", str);
					eleR.addAttribute("actionCode", transactionID);
					AKSLogs(100180, "" + iSN + "_" + iStation + "_" + str);
				}
			} else {
				isUnknowCase = true;
				return null;
			}
			return MSG;
		} catch (Exception e) {
			if(iClient==null) {
				Element Mroot = MSG.getRootElement();
				Element eleR = Mroot.element("body").addElement("result");
				eleR.addAttribute("errorCode", "1");
				eleR.addAttribute("errorText", "工位信息获取失败");
				eleR.addAttribute("actionCode", "0");
				return MSG;
			}
			String str = errCodeManagement.getErrText(e.getMessage());
			System.out.println(str);
			return null;
		}

	}

	public void AKSLogs(int iType, String ilogClientNews) {
		SQLtool.AKSLogs(iType, ilogClientNews);
	}

}
